package com.sskj.b70.v.activity;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.sskj.b70.MyAppLication;
import com.sskj.b70.R;
import com.sskj.b70.common.App;
import com.sskj.b70.common.AppManager;
import com.sskj.b70.common.Constants;
import com.sskj.b70.common.TabItem;
import com.sskj.b70.common.adapter.MyFragmentPagerAdapter;
import com.sskj.b70.common.rxbus2.RxBus;
import com.sskj.b70.common.rxbus2.RxBusCode;
import com.sskj.b70.common.rxbus2.Subscribe;
import com.sskj.b70.common.rxbus2.ThreadMode;
import com.sskj.b70.common.widget.NoticeDialog;
import com.sskj.b70.m.bean.AppVersionBean;
import com.sskj.b70.m.bean.UserInfo;
import com.sskj.b70.m.bean.rxbus.MainTabChange;
import com.sskj.b70.m.bean.rxbus.StockLevel;
import com.sskj.b70.p.activity.MainPresenter;
import com.sskj.b70.utils.APKVersionCodeUtils;
import com.sskj.b70.utils.SPUtils;
import com.sskj.b70.utils.ToastUtil;
import com.sskj.b70.v.base.BaseActivity;
import com.sskj.b70.v.fragment.AppUpDateFragment;
import com.sskj.b70.v.fragment.FabiFragment;
import com.sskj.b70.v.fragment.LevelTransactionFragment;
import com.sskj.b70.v.fragment.MarketBannerFragment;
import com.sskj.b70.v.fragment.MineFragment;
import com.sskj.b70.v.fragment.TransactionFragment;
import com.sskj.b70.v.widget.ViewPagerSlide;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Stack;

import butterknife.BindView;
import butterknife.OnClick;
import sskj.lee.appupdatelibrary.BaseUpdateDialogFragment;
import sskj.lee.appupdatelibrary.BaseVersion;

/**
 * create by Hey at 2018/5/3 18:45
 */
public class MainActivity extends BaseActivity<MainPresenter> {

    @BindView(R.id.viewPager)
    ViewPagerSlide viewPager;
    @BindView(R.id.tabLayout)
    CommonTabLayout tabLayout;
    @BindView(R.id.main_drawer_layout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.main_left_drawer_layout)
    LinearLayout mLeftLayout;

    public UserInfo mUserInfo;
    public boolean mDrawerIsOpen;
    public StockLevel stockLevel;

    /**
     * 0 买 1 卖
     */
    public int status;


    ArrayList<Fragment> fragmentList = new ArrayList<>();

    public boolean mTransactionFragmentUp = false;

    NoticeDialog dialog;
    Runnable runnable;
    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();

    public int index;
    public boolean mIsTransactionOpenDrawer = false;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    public MainPresenter getPresenter() {
        return new MainPresenter();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MyAppLication.isLogin()) {
            mPresenter.upDateUserInfo(); //更新用户数据
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int currentIndex = intent.getIntExtra("index", 0);
        this.status = intent.getIntExtra("type", 0);
        if (currentIndex == 2) {
            mUserInfo = (UserInfo) SPUtils.getBean(mActivity, Constants.SP_USER_INFO);
            viewPager.setCurrentItem(currentIndex);
        } else {
            viewPager.setCurrentItem(currentIndex);
        }
    }

//    @Subscribe(code = RxBusCode.USER_INFO_UPDATE, threadMode = ThreadMode.MAIN)
    public void updateUser() {
        mPresenter.upDateUserInfo();
    }

    @Override
    protected void onViewBinding() {
        if (MyAppLication.IS_FIRST_LOCK && MyAppLication.isLogin() && (Boolean) SPUtils.get(Constants.IS_GESTURE_ON, false, MyAppLication.getID())) {
            MyAppLication.IS_FIRST_LOCK = false;
            LockActivity.check(this);
        }
        MyAppLication.mainActvity=this;
        mUserInfo = (UserInfo) SPUtils.getBean(mActivity, Constants.SP_USER_INFO);
        if (!RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().register(this);
        }
//        mPresenter.getNotice();
        //设置菜单内容之外其他区域的背景色
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);//禁止滑动开启
        initFragment();
        mDrawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerOpened(View drawerView) {
                mDrawerIsOpen = true;
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                mDrawerIsOpen = false;
            }
        });
        mPresenter.getVersion();
        mPresenter.initWebSocket();
    }

    @Subscribe(code = Constants.PUSH_SOCKET_START, threadMode = ThreadMode.MAIN)
    public void restartSocket() {
        mPresenter.closeWebSocket();
        mPresenter.initWebSocket();
    }

    private void initFragment() {
        fragmentList.add(MarketBannerFragment.newInstance());
        fragmentList.add(TransactionFragment.newInstance());
        fragmentList.add(LevelTransactionFragment.newInstance(Constants.DEFAULT_COIN));
        fragmentList.add(FabiFragment.newInstance());
        fragmentList.add(new MineFragment());

        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.strMainActivity2), R.mipmap.icon_market_nor, R.mipmap.icon_market_pre));
        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.strMainActivity3), R.mipmap.icon_level_transaction_nor, R.mipmap.icon_level_transaction_pre));
        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.strMainActivity4), R.mipmap.icon_transaction_nor, R.mipmap.icon_transaction_pre));
        tabEntities.add(new TabItem("C2C", R.mipmap.fbjy_nor, R.mipmap.fbjy_pre));
        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.strMainActivity6), R.mipmap.icon_mine_nor, R.mipmap.icon_mine_pre));
        viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentList));
        viewPager.setSlide(false);
        tabLayout.setTabData(tabEntities);
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
//                if (MyAppLication.isLogin() && position == 4 && TextUtils.isEmpty(MyAppLication.getAccount())) {
//                    BindMobileActivity.start(MainActivity.this);
//                    return;
//                }
                viewPager.setCurrentItem(position, false);
                index = position;
                status = 0;
                RxBus.getDefault().send(Constants.DRAWER_OPEN);
                mUserInfo = (UserInfo) SPUtils.getBean(mActivity, Constants.SP_USER_INFO);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                tabLayout.setCurrentTab(position);
                index = position;
                status = 0;
                RxBus.getDefault().send(Constants.DRAWER_OPEN);

            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setCurrentTab(MainTabChange mainTabChange) {
        viewPager.setCurrentItem(mainTabChange.getPosition());
        index = mainTabChange.getPosition();
        status = 0;
        RxBus.getDefault().send(Constants.DRAWER_OPEN);


    }


    /**
     * @param context c
     * @param index   要跳转的页面index
     * @param type    0 买 1卖
     */
    public static void start(Context context, int index, int type) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("index", index);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }

    public void openDrawerLayout() {
        mDrawerLayout.openDrawer(Gravity.LEFT);
    }

    public void closeDrawerLayout() {
        mDrawerLayout.closeDrawers();
    }

    @OnClick(R.id.main_left_close)
    public void onViewClick() {
        mDrawerLayout.closeDrawers();
    }


    /**
     * 更新用户信息
     *
     * @param user 用户信息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUserInfo(UserInfo user) {
        if (user != null) {
            mUserInfo = user;
            SPUtils.putBean(mActivity, Constants.SP_USER_INFO, user);
        }
    }

    public void onVersionDataSuccess(AppVersionBean versionBean) {
        if (versionBean == null) {
            return;
        }
        String verName = APKVersionCodeUtils.getVerName(this);
        versionBean.setViewStyle(BaseVersion.NOTIFYCATION_STYLE);
        if (APKVersionCodeUtils.compareVersion(versionBean.getAppVersion(), verName) == 1) {
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            getFragmentManager().beginTransaction();
            AppUpDateFragment appUpDateFragment = new AppUpDateFragment();//自定义UI
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseUpdateDialogFragment.INTENT_KEY, versionBean);
            appUpDateFragment.setArguments(bundle);
            appUpDateFragment.show(fragmentTransaction, "update");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.MARKET:
                    onNewIntent(data);
                    break;
                case Constants.PAY_PWD_INPUT:
                    LevelTransactionFragment fragment = (LevelTransactionFragment) getSupportFragmentManager().findFragmentByTag(LevelTransactionFragment.class.getSimpleName());
                    if (fragment != null) {
                        fragment.onActivityResult(requestCode, resultCode, data);
                    }
                    break;
            }
        }

    }


    public void showNotice(String tpgg) {
        dialog = new NoticeDialog.Builder(this)
                .cancelable(false)
                .canceledOnTouchOutside(false)
                .loadText(tpgg)
                .build();
        dialog.show();

        Handler handler = new Handler();

        runnable = new Runnable() {
            int i = 4;

            @Override
            public void run() {
                if (i != 0) {
                    Log.e("MAIN", i + "");
                    handler.postDelayed(runnable, 1000);
                    dialog.getButton().setText("(" + i + ")" + App.INSTANCE.getString(R.string.strMainActivity14));
                    dialog.getButton().setEnabled(false);
                    i--;
                } else {
                    dialog.getButton().setText(App.INSTANCE.getString(R.string.strMainActivity14));
                    dialog.getButton().setEnabled(true);
                }
            }
        };
        handler.postDelayed(runnable, 1000);
    }

    public boolean checkPwdStatus() {
        if (mUserInfo != null) {
            if (!TextUtils.isEmpty(mUserInfo.tpwd)) {
                return true;
            } else {
                ToastUtil.showShort(getResources().getString(R.string.none_zf_pwd));
                startActivity(new Intent(mActivity, SecurityCenterActivity.class));
                return false;
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        RxBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private static long mPreTime;

    /**
     * 统一退出控制
     */
    @Override
    public void onBackPressed() {
        Stack<Activity> allActivities = AppManager.getAppManager().getAllActivities();
        if (mDrawerIsOpen) {
            mDrawerLayout.closeDrawers();
            return;
        }
        if (allActivities.size() <= 1) {
            if (System.currentTimeMillis() - mPreTime > 2000) {// 两次点击间隔大于2秒
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strMainActivity16));
                mPreTime = System.currentTimeMillis();
                return;
            }
        }
        super.onBackPressed();
        MyAppLication.IS_FIRST_LOCK = true;
        MyAppLication.IS_HOME = false;
        int pid = android.os.Process.myPid();
        String cmd = "kill -9 " + pid;
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
